﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessLayer;
using BusinessLayer.VDataEntities;
using System.Web;
using CustomerServiceCenter.Models;
using CustomerServiceCenter.Helper;
using BusinessLayer.DatabaseEntities;
using System.Data;




namespace CustomerServiceCenter.Controllers.API
{

    public class TicketsController : ApiController
    {
        //存放上传的报表
        private static List<Report> reports = new List<Report>();
        //存放下载的报表
        //private static List<TicketPCModel> ticketPcInfo = new List<TicketPCModel>();
        public List<VOperator> GetOperatorInfo()
        {
            List<VOperator> operatorList = TicketBusiness.GetOperatorInfo();
            return operatorList;
        }

        [LoginAuthorize]
        public List<VOperator> GetOperatorInfo(long TicketID, int isFromWeChat = 1)
        {
            var loginInfo = HttpContext.Current.Session["adminLoginInfo"] as Operator;
            List<VOperator> operatorList = new List<VOperator>();

            VTicketsRequestInfo ticketDetail = TicketBusiness.GetTicketDetails((int)TicketID, isFromWeChat);
            long[] operatorID = ProjectBusiness.GetOperatorID(ticketDetail.ApplicationID);
            operatorList = ProjectBusiness.GetOperatorInfoById(operatorID);
            return operatorList;
        }

        [LoginAuthorize]
        public List<VApplication> GetApplicationInfo()
        {
            var loginInfo = HttpContext.Current.Session["adminLoginInfo"] as Operator;
            List<VApplication> applicationList = new List<VApplication>();
            if (loginInfo.RoleID == 1)
            {
                applicationList = ProjectBusiness.GetApplicationInfo();
            }
            else
            {
                long[] applicationId = ProjectBusiness.GetApplicationIDOrOperatorID(loginInfo.ID);
                applicationList = ProjectBusiness.GetApplicationInfoById(applicationId);

            }

            return applicationList;
        }

        public List<VEndUser> GetEndUserInfo()
        {

            List<VEndUser> endUserInfo = TicketBusiness.GetEndUserInfo();
            return endUserInfo;
        }

        public List<VTicketCommentsHistory> GetCommentsHistory(long TicketID)
        {
            List<VTicketCommentsHistory> commnetsHistory = TicketBusiness.GetCommentsHistory(TicketID);
            if (commnetsHistory.Count > 0)
            {
                return commnetsHistory;
            }
            else
            {
                return null;
            }
        }

        public List<VImage> GetImageInfo(long TicketID)
        {
            List<VImage> list = TicketBusiness.GetImage(TicketID);
            return list;
        }

        #region ajax分页
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="status"></param>
        /// <param name="operatorId"></param>
        /// <param name="project"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [LoginAuthorize]
        [HttpPost]
        public TicketsAndMaxPage GetTicketsRequestInfo(TicketsRequestModel model)
        {

            DateTime StartDate = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            DateTime EndDate = DateTime.Now.AddDays(1);
            var loginInfo = HttpContext.Current.Session["adminLoginInfo"] as Operator;
            long[] applicationID = ProjectBusiness.GetApplicationIDOrOperatorID(loginInfo.ID);

            if (null != (model.startDate))
            {
                StartDate = Convert.ToDateTime(model.startDate);
            }
            if (null != (model.endDate))
            {
                EndDate = Convert.ToDateTime(model.endDate);
            }

            int maxPage = TicketBusiness.GetCount(model.status, model.project, StartDate, EndDate, model.operatorId, loginInfo.RoleID, applicationID, model.type, model.IsFromWeChat,model.Priority,model.IssueType);
            if (maxPage < model.pageSize)
            {
                maxPage = 1;
            }
            else
            {
                maxPage = maxPage % model.pageSize == 0 ? maxPage / model.pageSize : maxPage / model.pageSize + 1;
            }

            List<VTicketsRequestInfo> ticketInfo = TicketBusiness.FindTickets(model.status, model.project, model.operatorId, StartDate, EndDate, model.pageIndex, model.pageSize, loginInfo.RoleID, applicationID, model.type, model.IsFromWeChat, model.Priority, model.IssueType);
            List<TicketPCModel> ticketPcInfo = new List<TicketPCModel>();
            foreach (var item in ticketInfo)
            {
                //var assignerName = TicketBusiness.GetOperatorInfoById((long)item.Assigner).Name;
                //var openBy = TicketBusiness.GetEndUserInfoById
                string assignerName = null;
                string statusInfo = "New";
                string projectName = "";
                VOperator operatorInfo = new VOperator();
                if (item.AssignerInfo.ID != null)
                {
                    operatorInfo = TicketBusiness.GetOperatorInfo((long)item.AssignerInfo.ID).FirstOrDefault();
                    statusInfo = EnumDescripte.GetName(typeof(ShortStatus), item.Status);

                }
                if (operatorInfo != null)
                {
                    assignerName = operatorInfo.Name;

                }

                TicketPCModel tickets = new TicketPCModel();
                if (item.IsFromWeChat == 2)
                {
                    tickets.TicketNo = item.ReportTicketNo;
                }
                else
                {
                    tickets.TicketNo = item.OrderNumber;
                }
                List<VApplication> list = ProjectBusiness.GetApplicationInfo(item.ApplicationID);
                if (null != list && list.Count > 0)
                {

                    projectName = list[0].Name;
                }
                tickets.OpenBy = item.User.Name;
                tickets.ID = item.TicketID;
                tickets.Project = projectName;
                tickets.Client = item.Client.Name;
                tickets.OpenDate = item.SubmitDate;
                tickets.State = statusInfo;
                tickets.IssueType = item.IssueTypeDescription;
                tickets.AssignTo = assignerName;
                tickets.Ratings = Convert.ToInt32(item.ServiceRate);
                tickets.IsFromWeChat = item.IsFromWeChat;
                ticketPcInfo.Add(tickets);
            }

            TicketsAndMaxPage info = new TicketsAndMaxPage()
            {
                MaxPage = maxPage,
                TicketPCModelList = ticketPcInfo
            };
            return info;
        }
        #endregion 结束分页
        /// <summary>
        /// 获取上传历史
        /// </summary>
        /// <returns></returns>
        [LoginAuthorize]
        [HttpPost]
        public List<string> GetImportView()
        {
            var user = HttpContext.Current.Session["adminLoginInfo"] as Operator;
            string userName = user.UserName;
            string path = System.Web.Hosting.HostingEnvironment.MapPath("/Content/File/Log.xml");
            List<string> date = ImportLogToXML.GetImportHistory(userName, path);
            return date;
        }
        /// <summary>
        /// 上传Ticket预览
        /// </summary>
        /// <returns></returns>
        [LoginAuthorize]
        public List<Report> ImportTicketView(long CustomerID, long ProjectID)
        {
            //Excel表格和类对应的匹配
            Dictionary<string, string> mapping = ExcelToClassMapping.GetMapping();
            //mapping.Add("CustomerID", CustomerID.ToString());
            //mapping.Add("ProjectID", ProjectID.ToString());
            HttpPostedFile file = null;
            for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
            {
                file = HttpContext.Current.Request.Files[0];
                reports = ExcelUntils.GetObjectFromExcel<Report>(file.InputStream, CustomerID, ProjectID, mapping);
            }
            return reports;
        }
        /// <summary>
        /// 上传员工报表
        /// </summary>
        [LoginAuthorize]
        public string UploadTickets()
        {
            //上传者
            string userName = (HttpContext.Current.Session["adminLoginInfo"] as Operator).UserName;
            List<Report> list = null;
            if (reports.Count > 0)
            {
                list = reports;
            }
            else
            {
                return "你还没有上传Excel,！";
            }
            //验证数据
            Dictionary<int, string> error = AuthcationDataHelper.CheckImportData(list);
            if (error.Count > 0)
            {
                for (int j = 0; j < error.Count; j++)
                {
                    Dictionary<int, string>.KeyCollection key = error.Keys;
                    foreach (var line in key)
                    {
                        string errorMsg = string.Empty;
                        error.TryGetValue(line, out errorMsg);
                        return string.Format("对不起,您的第{0}行{1}", line, errorMsg);
                    }
                }
            }
            List<long> ticketids = new List<long>();
            //插入数据
            foreach (var item in list)
            {
                if (item.TicketNo != null)
                {
                    long id = TicketBusiness.ImportTickets(item);
                    ticketids.Add(id);
                }
            }
            //记录操作日志
            if (ticketids != null && ticketids.Count > 0)
            {
                string path = HttpContext.Current.Server.MapPath("/Content/File/Log.xml");
                ImportLogToXML.InsertXML(ticketids, path, userName);
            }
            return null;
        }


        /// <summary>
        /// AssignOrModifyStatus
        /// </summary>
        /// <param name="ticketId"></param>
        /// <param name="assinger"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [LoginAuthorize]
        [HttpPost]
        public string AssignOrModifyStatus(AssignOrModifyStatusModel model)
        {
            string message = "";
            try
            {
                if (model.Assigner == 0)
                {
                    return "Assigner" + "不能为空";
                }
                if (model.Status <= 0)
                {
                    return "请安排状态";
                }
                var loginInfo = HttpContext.Current.Session["adminLoginInfo"] as Operator;
                string assingerName = TicketBusiness.GetOperatorInfo(model.Assigner).FirstOrDefault().Name;
                TicketBusiness.AssignAndModifyStatus(model.IsFromWeChat, model.TicketID, model.Assigner, model.Status);
                if (model.Status == (int)TicketStatusType.Resolved && model.Solution != null)
                {
                    AddCommnets(model.Solution, model.TicketID, model.Status, model.IsFromWeChat);
                }
                string Type = null;
                if (model.IssueType != 0)
                {
                    List<IssueType> list = ProjectBusiness.GetIssueTypeInfoBySome(model.IssueType);
                    if (null != list && list.Count > 0)
                    {
                        Type = list[0].Type;
                    }
                }
                TicketBusiness.ModifyTicketsInfo(model.TicketID, model.Description, model.IssueType, Type, model.PriorityNum);
                TicketBusiness.AddOperationLog(model.TicketID, loginInfo.UserName, model.Status);
                

                LogHelper.Info(loginInfo.UserName + "对ticketId = " + model.TicketID + "的人员安排和状态进行了修改" + "将人员更改为" + assingerName + "将状态更改为" + model.Status);
                message = "success";
            }
            catch (Exception)
            {
                message = "ModifyError";
                //throw;
            }
            return message;
        }
        [HttpGet]
        public string AddCommnets(string commentsVal, int ticketID, int status,int isFromWeChat)
        {
            try
            {
                var loginInfo = HttpContext.Current.Session["adminLoginInfo"] as Operator;
                string endUserName = TicketBusiness.GetEndUserInfo(TicketBusiness.GetTicketDetails(ticketID, isFromWeChat).User.ID).FirstOrDefault().Name;
                VTicketStatus ticketStatus = new VTicketStatus()
                {

                    actorName = loginInfo.UserName,
                    Comments = commentsVal,
                    ticketID = ticketID,
                    ticketStatus = status
                };
                if (commentsVal != null)
                {
                    TicketBusiness.AddComments(ticketStatus);
                    //微信发消息
                    WeChatHelper wechat = new WeChatHelper();
                    VTicketsRequestInfo ticket = TicketBusiness.GetTicketDetails(ticketID, isFromWeChat);
                    Client client = ClientBusiness.GetClientByEndUserID(ticket.User.ID);
                    if (client != null)
                    {
                        string sendMsg = string.Format("编号:{0}的请求状态已更新为:{2}.\n工程师留言:{1}.\n温馨提示:如果问题已解决请进入请求并关闭问题", ticket.OrderNumber, (string.IsNullOrWhiteSpace(commentsVal) ? "." : (commentsVal)), EnumDescripte.GetEnumDeScription((ShortStatus)status));
                        WeiXinMessage msg = new WeiXinMessage()
                        {
                            ToUserName = endUserName,
                            MsgContent = sendMsg,
                            //openid = openid,
                        };
                        //wechat.SendServiceMessage(msg, client);
                       // wechat.SendMessage(msg, client);
                    }
                    return null;
                }
                else
                {
                    return "comment is empty";
                }
            }
            catch (Exception)
            {
                return "add comment error";
                // throw;
            }
        }


        [HttpGet]
        public List<VApplication> GetApplicationInfoBySome(long ClientID)
        {
            List<VApplication> list = ProjectBusiness.GetApplicationInfo(0, ClientID);
            return list;
        }

        /// <summary>
        /// 下载报表
        /// </summary>
        /// <returns></returns>
        //public static string DownloadData() {
        //  DataTable data =  ExcelUntils.ListToDataTable(ticketPcInfo);
        //  bool flag = ExcelUntils.DataTableToExcel(data, "F:/myxls.xls");
        //  if (flag)
        //  {
        //      return "下载成功";
        //  }
        //  else
        //  {
        //      return "下载失败";
        //  }
        //}

    }
}
